using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SumerCoreDevOps.Application.Workflows.Commands;
using SumerCoreDevOps.Application.Workflows.Queries;
using SumerCoreDevOps.Shared.Models;
using SumerCoreDevOps.Application.Dtos.Requests.Workflows;
using SumerCoreDevOps.Application.Dtos.Responses.Workflows;
namespace SumerCoreDevOps.ControlApi.Controllers;

/// <summary>
/// 工作流管理接口
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class WorkflowController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<WorkflowController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="mediator">MediatR 中介者</param>
    /// <param name="logger">日志记录器</param>
    public WorkflowController(IMediator mediator, ILogger<WorkflowController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有启用的工作流
    /// </summary>
    /// <returns>返回包含所有已启用工作流的列表,每个工作流包括ID、名称、描述、版本、是否启用等信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回工作流列表</response>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<List<Domain.Entities.WorkflowDefinition>>), 200)]
    public async Task<IActionResult> GetWorkflows()
    {
        var workflows = await _mediator.Send(new GetWorkflowsQuery());
        return Ok(ApiResponse.Ok(workflows));
    }

    /// <summary>
    /// 获取工作流详情
    /// </summary>
    /// <param name="id">工作流ID</param>
    /// <returns>返回指定工作流的完整信息对象,包括ID、名称、描述、版本、配置、创建时间等;如果工作流不存在则返回404状态码和失败信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回工作流信息</response>
    /// <response code="404">工作流不存在</response>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<Domain.Entities.WorkflowDefinition>), 200)]
    [ProducesResponseType(typeof(ApiResponse<object>), 404)]
    public async Task<IActionResult> GetWorkflow(long id)
    {
        var workflow = await _mediator.Send(new GetWorkflowByIdQuery(id));

        if (workflow == null)
        {
            return NotFound(ApiResponse.Fail($"工作流 {id} 不存在"));
        }

        return Ok(ApiResponse.Ok(workflow));
    }

    /// <summary>
    /// 创建工作流
    /// </summary>
    /// <param name="request">创建工作流请求</param>
    /// <returns>返回新创建的工作流完整信息对象,包括自动生成的工作流ID、名称、描述、版本等字段;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功创建工作流</response>
    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<Domain.Entities.WorkflowDefinition>), 200)]
    public async Task<IActionResult> CreateWorkflow([FromBody] CreateWorkflowRequest request)
    {
        var command = new CreateWorkflowCommand(
            request.Name,
            request.Description,
            request.Version,
            User.Identity?.Name);

        var workflow = await _mediator.Send(command);
        return Ok(ApiResponse.Ok(workflow));
    }

    /// <summary>
    /// 验证工作流配置是否正确
    /// </summary>
    /// <param name="id">工作流ID</param>
    /// <returns>返回验证结果对象,包含IsValid布尔值和Errors错误列表;如果工作流配置正确IsValid为true且Errors为空;否则IsValid为false且Errors包含具体错误信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">返回验证结果</response>
    [HttpPost("{id}/validate")]
    [ProducesResponseType(typeof(ApiResponse<ValidationResult>), 200)]
    public async Task<IActionResult> ValidateWorkflow(long id)
    {
        var result = await _mediator.Send(new ValidateWorkflowQuery(id));

        return Ok(ApiResponse.Ok(new ValidationResult
        {
            IsValid = result.IsValid,
            Errors = result.Errors
        }));
    }

    /// <summary>
    /// 启用工作流
    /// </summary>
    /// <param name="id">工作流ID</param>
    /// <returns>返回成功提示信息,数据封装在ApiResponse对象中;启用后的工作流可以被流水线使用</returns>
    /// <response code="200">成功启用工作流</response>
    [HttpPost("{id}/enable")]
    [ProducesResponseType(typeof(ApiResponse<object>), 200)]
    public async Task<IActionResult> EnableWorkflow(long id)
    {
        await _mediator.Send(new EnableWorkflowCommand(id));
        return Ok(ApiResponse.Ok(null));
    }

    /// <summary>
    /// 禁用工作流
    /// </summary>
    /// <param name="id">工作流ID</param>
    /// <returns>返回成功提示信息,数据封装在ApiResponse对象中;禁用后的工作流不能被新流水线使用,但不影响已创建的流水线</returns>
    /// <response code="200">成功禁用工作流</response>
    [HttpPost("{id}/disable")]
    [ProducesResponseType(typeof(ApiResponse<object>), 200)]
    public async Task<IActionResult> DisableWorkflow(long id)
    {
        await _mediator.Send(new DisableWorkflowCommand(id));
        return Ok(ApiResponse.Ok(null));
    }
}
